<template>
  <div>
    <div class="common-choice">
      <div v-for="item in form.options" :key="item.code" class="common-choice-item">
        <div class="item-label">{{item.code}}</div>
        <div class="edit-wrap">
          <editor v-model="item.content" :readOnly="readOnly" :min-height="180"/>
        </div>
      </div>
      <div v-if="!readOnly" class="choice-more">
        <i class="el-icon-plus" style="color: #409eff"></i><span @click="onAdd">添加选项</span>
      </div>
    </div>
    <div class="form-label2">
      <label>答案</label>
      <p>（请在下方下拉框中对选项进行排序【顺序为：从左往右】）</p>
    </div>
    <div class="third-indent answer">
      <el-row :gutter="10">
        <el-col v-for="(item, index) in form.answer" :key="index" :span="4">
          <el-select v-model="item.content" :disabled="readOnly" placeholder="请选择">
            <el-option
              v-for="selectItem in form.options"
              :key="selectItem.code"
              :label="selectItem.code"
              :value="selectItem.code">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
  
<script>
// 排序题
const letterList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'];
const defaultForm = JSON.stringify({
  options: [{ code: 'A', content: '' }],
  answer: [{ content: 'A' }]
});

export default {
  name: "Sortable",
  props: {
    initialVals: {
      type: Object,
      default: () => ({}),
    },
    clean: {
      type: String,
      default: '',
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    validate: {  // 触发内层表单校验
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: JSON.parse(defaultForm)
    }
  },
  watch: {
    initialVals: {
      handler(val) {
        if (Object.keys(val).length > 0) {
          let formData = JSON.parse(JSON.stringify(val));
          if (formData.answer) {
            this.form = { ...formData, answer: formData.answer.sort.map(item => ({ content: item })) };
          }
        }
      },
      immediate: true,
    },
    validate: {
      handler(val) {
        // TODO: 校验表单
        console.log(val);
        this.$emit('onValid', true);
      }
    },
    clean: {
      handler(val) {
        if (val) this.form = JSON.parse(defaultForm);
      }
    },
    form: {
      handler(val) {
        let form = { ...JSON.parse(JSON.stringify(val)), answer: { sort: val.answer.map(item => item.content) } };
        this.$emit('change', form);
      },
      deep: true
    }
  },
  methods: {
    onAdd() {
      const options = this.form.options.slice();
      const answer = JSON.parse(JSON.stringify(this.form.answer));
      options.push({ code: letterList[options.length], content: '' });
      answer.push({ content: '' });
      this.form = { options, answer };
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
    